import {
  PicRightOutlined,
  VerticalAlignBottomOutlined,
  VerticalAlignMiddleOutlined,
} from '@ant-design/icons';
import Editor, { EditorProps, loader } from '@monaco-editor/react';
import { App, Flex, Segmented, Space } from 'antd';
import * as monaco from 'monaco-editor';
import React from 'react';
import SfwButton from '../../common/SfwButton';

loader.config({
  paths: { vs: 'https://g.alicdn.com/code/lib/monaco-editor/0.48.0/min/vs' },
});

export type SfwCodeEditorProps = Omit<EditorProps, 'onChange'> & {
  language: 'json' | 'javascript';
  theme: string;
  containerProps?: any;
  value?: string;
  onChange: (value?: string) => void;
};

const SfwCodeEditor: React.FC<SfwCodeEditorProps> = (props) => {
  const {
    value,
    onChange,
    language = 'json',
    theme: themeProps,
    containerProps,
    ...rest
  } = props;
  const { message } = App.useApp();
  const [theme, setTheme] = React.useState<string>(themeProps || 'VsDark');
  const [wordWrap, setWordWrap] = React.useState<boolean>(true);

  // let extensions = [EditorView.lineWrapping];
  // if (language === 'javascript') {
  //   extensions = [...extensions, javascript({ jsx: true })];
  // } else {
  //   extensions = [...extensions, json()];
  // }

  const handleFormat = () => {
    try {
      onChange(JSON.stringify(JSON.parse(value || ''), null, 2));
    } catch {
      message.warning('JSON 格式不正确');
    }
  };

  const handleFormatString = () => {
    try {
      onChange(JSON.stringify(JSON.parse(value || '')));
    } catch {
      message.warning('JSON 格式不正确');
    }
  };

  const handleThemeChange = (theme: string) => {
    setTheme(theme);
  };
  const handleWordWrap = () => {
    setWordWrap(!wordWrap);
  };
  const themeList = {
    VsDark: 'vs-dark',
    Light: 'light',
  };

  const options: monaco.editor.IStandaloneEditorConstructionOptions = {
    acceptSuggestionOnCommitCharacter: true,
    acceptSuggestionOnEnter: 'on',
    accessibilitySupport: 'auto',
    autoIndent: 'none',
    automaticLayout: true,
    codeLens: true,
    colorDecorators: true,
    contextmenu: true,
    cursorBlinking: 'blink',
    cursorSmoothCaretAnimation: 'off',
    cursorStyle: 'line',
    disableLayerHinting: false,
    disableMonospaceOptimizations: false,
    dragAndDrop: false,
    fixedOverflowWidgets: false,
    folding: true,
    foldingStrategy: 'auto',
    fontLigatures: false,
    formatOnPaste: false,
    formatOnType: false,
    hideCursorInOverviewRuler: false,
    links: true,
    mouseWheelZoom: false,
    multiCursorMergeOverlapping: true,
    multiCursorModifier: 'alt',
    overviewRulerBorder: true,
    overviewRulerLanes: 2,
    quickSuggestions: true,
    quickSuggestionsDelay: 100,
    readOnly: false,
    renderControlCharacters: false,
    renderFinalNewline: 'on',
    renderLineHighlight: 'all',
    renderWhitespace: 'none',
    revealHorizontalRightPadding: 30,
    roundedSelection: true,
    rulers: [],
    tabSize: 2,
    scrollBeyondLastColumn: 5,
    scrollBeyondLastLine: true,
    selectOnLineNumbers: true,
    selectionClipboard: true,
    selectionHighlight: true,
    showFoldingControls: 'mouseover',
    smoothScrolling: false,
    suggestOnTriggerCharacters: true,
    wordBasedSuggestions: 'allDocuments',
    wordSeparators: '~!@#$%^&*()-=+[{]}|;:\'",.<>/?`',
    wordWrap: wordWrap ? 'on' : 'off',
    wordWrapBreakAfterCharacters: '\t})]?|&,;',
    wordWrapBreakBeforeCharacters: '{([+',
    wordWrapColumn: 80,
    wrappingIndent: 'none',
  };

  return (
    <>
      <Flex
        vertical
        gap={'middle'}
        style={{ width: '100%', height: '100%' }}
        {...containerProps}
      >
        <Space style={{ flex: '0 0 auto' }} wrap>
          <SfwButton
            onClick={handleFormat}
            icon={<VerticalAlignBottomOutlined />}
            tooltip={'格式化'}
          />
          <SfwButton
            onClick={handleFormatString}
            icon={<VerticalAlignMiddleOutlined />}
            tooltip={'压缩'}
          />
          <SfwButton
            onClick={handleWordWrap}
            icon={<PicRightOutlined />}
            tooltip={'自动换行'}
          />
          <Segmented
            options={['VsDark', 'Light']}
            onChange={handleThemeChange}
          />
        </Space>
        <div
          style={{
            flex: '1 1 auto',
            overflowY: 'scroll',
            height: rest.height || '200px',
          }}
        >
          <Editor
            value={value}
            onChange={onChange}
            width={'100%'}
            // @ts-ignore
            theme={themeList[theme]}
            defaultLanguage={language}
            options={options}
            {...rest}
          />
        </div>
      </Flex>
    </>
  );
};

export default SfwCodeEditor;
